package com.icangya.Utils;

import com.icangya.Value.StaticValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by cangya4 on 2017/4/25.
 */
public class ThreadUtils {
    // 定义一个私有构造方法
    private ThreadUtils() {

    }


    Logger logger = LoggerFactory.getLogger(this.getClass());

    //定义一个静态私有变量(不初始化，不使用final关键字，使用volatile保证了多线程访问时instance变量的可见性，避免了instance初始化时其他变量属性还没赋值完时，被另外线程调用)
    private static volatile ThreadUtils instance;

    //定义一个共有的静态方法，返回该类型实例
    public static ThreadUtils getIstance() {
        // 对象实例化时与否判断（不使用同步代码块，instance不等于null时，直接返回对象，提高运行效率）
        if (instance == null) {
            //同步代码块（对象未初始化时，使用同步代码块，保证多线程访问时对象在第一次创建后，不再重复被创建）
            synchronized (ThreadUtils.class) {
                //未初始化，则初始instance变量
                if (instance == null) {
                    instance = new ThreadUtils();
                }
            }
        }
        return instance;
    }

    private ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    //private Thread thread = new Thread();

    public void execute(Runnable runnable) {
        cachedThreadPool.execute(runnable);
    }

//    /**
//     * 循环线程
//     *
//     * @param runnable 需要执行的代码
//     * @param time     循环间隔
//     * @throws InterruptedException
//     */
//    public void execute(Runnable runnable, Integer time) throws InterruptedException {
//        cachedThreadPool.execute(runnable);
//        Thread.sleep(time);
//        this.execute(runnable, time);
//    }


    /**
     * 循环线程
     *
     * @param runnable 需要执行的代码
     * @param type     循环类型
     * @throws InterruptedException
     */
    public void executeNew(Runnable runnable, Integer type) throws InterruptedException {
        int time = 0;
        switch (type) {
            case 1:
                time = StaticValue.SCAN_INTERVAL001;
                break;
            case 6:
                time = StaticValue.SCAN_INTERVAL006;
                break;
            case 24:
                time = StaticValue.SCAN_INTERVAL024;
                break;
            case 200:
                time = StaticValue.SCAN_INTERVAL200;
                break;
            default:
                break;
        }
        runnable.run();//真正执行的地方
        Thread.sleep(time);//等待
    }


}
